/*
  The MIT License
  
  Copyright (c) 2009 smath project
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:
  
  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.
  
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.
*/
package pl.smath.expression.parser.text;

import java.util.Vector;

import pl.smath.expression.model.EqualityRelationTerm;
import pl.smath.expression.model.ExponentiationTerm;
import pl.smath.expression.model.FractionTerm;
import pl.smath.expression.model.NumberTerm;
import pl.smath.expression.model.ProductTerm;
import pl.smath.expression.model.OrderRelationTerm;
import pl.smath.expression.model.RootTerm;
import pl.smath.expression.model.SumTerm;
import pl.smath.expression.model.VariableTerm;
import pl.smath.expression.model.Term;


/**
 * Parsuje wyrazenie dostarczone jako tekst
 * @author klangner
 *
 */
public class TextParser {
	
	/**
	 * tokenizer do pobierania token z wejscia
	 */
	private Tokenizer	tokenizer;

	
	/**
	 * Parse given expression
	 * @return Root node
	 */
	public Term parse(String exp){

		tokenizer = new Tokenizer(exp);
		return relation();
	}

	/**
	 * Pobranie relacji
	 * @return
	 */
	private Term relation(){
		Term output;
		Term left = sum();
		
		output = left;
		if(tokenizer.hasMoreTokens()){
			Token token = tokenizer.nextToken();
			Term right = sum();
			if(token.getText().charAt(0) == '='){
				
				output = new EqualityRelationTerm(left, right);
			} 
			else if(token.getText().compareToIgnoreCase("!=") == 0){
				
				output = new EqualityRelationTerm(left, right);
				output.setNegative(true);
			} 
			else {
				
				output = new OrderRelationTerm(token.getText(), left, right);
			}
		}
		
		return output;
	}	
	
	/**
	 * Pobranie sumy wyrazen z wejscia
	 * @return
	 */
	private Term sum(){
		
		Vector<Term> terms = new Vector<Term>();
		Token token;
		Term term;

		term = multi();
		terms.add(term);
	    
	    while(tokenizer.hasMoreTokens()){
	    	
	    	token = tokenizer.nextToken();
	    	if(token.getText().charAt(0) == '+'){
	    		terms.add(multi());
	    	}
	    	else if(token.getText().charAt(0) == '-'){
	    		term = multi();
	    		term.setNegative(!term.isNegative());
	    		terms.add(term);
	    	}
	    	else{
	    		//push back token
	    		tokenizer.pushback(token);
	    		break;
	    	}
	    }
	    
	    if(terms.size() > 1){
	    	SumTerm sumTerm = new SumTerm();
	    	sumTerm.addTerms(terms);
	    	return sumTerm;
	    }
	    else{
	    	return terms.get(0);
	    }
	}

	
	/**
	 * Pobranie iloczynu wyrazen z wejscia
	 * @return
	 */
	private Term multi()
	{
	    Vector<Term> terms = new Vector<Term>();
	    Token token;
	    boolean isNegative = false;

	    if(!tokenizer.hasMoreTokens())
	    	return null;
	    
		token = tokenizer.nextToken();
		
		while(token.getText().charAt(0) == '-'){
			isNegative = !isNegative;
			token = tokenizer.nextToken();
		}
			
		tokenizer.pushback(token);
	    
	    terms.add(fraction());

	    while(tokenizer.hasMoreTokens()){
	    	
	    	token = tokenizer.nextToken();
	    	if(token.getText().charAt(0) == '*'){
	    		terms.add(fraction());
	    	}
	    	else if( token instanceof SymbolToken || 
	    			(token instanceof BracketToken && token.getText().charAt(0) == '(') )
	    	{
	    		tokenizer.pushback(token);
	    		terms.add(fraction());
	    	}
	    	else{
	    		//push back token
	    		tokenizer.pushback(token);
	    		break;
	    	}
	    }
	    
	    if(terms.size() > 1){
	    	ProductTerm term = new ProductTerm();
	    	term.addTerms(terms);
	    	term.setNegative(isNegative != term.isNegative());
	    	return term;
	    }
	    else{
	    	terms.get(0).setNegative(isNegative != terms.get(0).isNegative());
	    	return terms.get(0);
	    }
	    
	}
	
	
	/**
	 * Pobranie iloczynu wyrazen z wejscia
	 * @return
	 */
	private Term fraction()
	{
	    Term denominator;
	    Term term;

	    term = pow();

	    while(tokenizer.hasMoreTokens()){
	    	
	    	Token token = tokenizer.nextToken();
	    	if(token.getText().charAt(0) == '/'){
	    		denominator = pow();
	    		term = new FractionTerm(term, denominator);
	    	}
	    	else{
	    		//push back token
	    		tokenizer.pushback(token);
	    		break;
	    	}
	    }
    	
    	return term;
	}
	
	
	/**
	 * Pobranie elementu a^b
	 * @return
	 */
	private Term pow()
	{
	    Term exponent;
	    Term term;
	    Token 	token;

		term = unary();

	    while(tokenizer.hasMoreTokens()){
	    	
	    	token = tokenizer.nextToken();
	    	if(token.getText().charAt(0) == '^'){
	    		exponent = unary();
	    		term = new ExponentiationTerm(term, exponent);
	    	}
	    	else if(token.getText().charAt(0) == '$'){
	    		exponent = unary();
	    		term = new RootTerm(term, exponent);
	    	}
	    	else{
	    		//push back token
	    		tokenizer.pushback(token);
	    		break;
	    	}
	    }
    	
    	return term;
	}
	
	/**
	 * Pobranie elementu poprzedzonego znakiem -
	 * @return
	 */
	private Term unary(){
	    
		Token 	token = tokenizer.nextToken();
		
		if(token != null){
			if(token.getText().charAt(0) == '-'){
				Term 	term = element();
				term.setNegative(true);
				return term;
			}
			else{
				tokenizer.pushback(token);
				return element();
			}
		}
		
		return null;
	}

	
	/**
	 * Pobranie elementu z wejscia
	 * Elementem jest liczba, symbol lub wyrazenie w nawiasach
	 */
	private Term element()
	{
		Token token = tokenizer.nextToken();
		
		if(token instanceof NumberToken)
			return new NumberTerm( token.getText() );
		else if(token instanceof SymbolToken)
			return new VariableTerm( token.getText() );
		else{
			if(token.getText().charAt(0) == '('){

				Term term = sum();
				token = tokenizer.nextToken();
				if(token.getText().charAt(0) != ')')
					return null;
				else
					return term;
			}
		}
		
		return null;
		
	}


}
